//
//  GameMainViewController.m
//  linkingGame
//
//  Created by zw wu on 15/4/4.
//  Copyright (c) 2015年 com.jinWu. All rights reserved.
//

#import "GameMainViewController.h"
#import <GoogleMobileAds/GoogleMobileAds.h>
#import "ClickButton.h"
#import "ProgressView.h"
#import "GameMainView.h"
#import "PosMatcher.h"
#import "ClassPassMaker.h"
#import "ChallengePassMaker.h"
#import "MapMaker.h"

typedef enum InitType
{
    InitFromLocal = 0,
    InitFromTemplate,
    InitFromData
}InitType;

@interface GameMainViewController ()<GADBannerViewDelegate>

@property (nonatomic,strong) GADBannerView *banner;
@property (nonatomic,strong) id<LevelData> levelData;

@property(nonatomic, strong)NSMutableArray* matchBtnArray; //等待匹配的按钮
@property(nonatomic, strong)LLKPosMatcher* matcher;

@property(nonatomic, assign)CGFloat beginX;
@property(nonatomic, assign)CGFloat beginY;

@property(nonatomic, strong)CAEmitterLayer* emitterLayer;
@end

@implementation GameMainViewController

- (BOOL)prefersStatusBarHidden
{
    return YES;//隐藏为YES，显示为NO
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    BOOL isNotShowAds = [[NSUserDefaults standardUserDefaults] boolForKey:@"KReplaceColorRemoveAds"];
    if (isNotShowAds)
    {
        self.banner.hidden = YES;
    }
    else
    {
        self.banner.hidden = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    }
    
    if (self.gameMode == KClassicMode)
        self.levelData = [ClassPassMaker bulitMapWithLevel:self.level];
    else
        self.levelData = [ChallengePassMaker bulitMapWithLevel:self.level];
    //获取开始位置
    NSUInteger btnWidth = GetBtnSizeByDevice();
    CGRect mainRect = [UIScreen mainScreen].bounds;
    self.beginX = (mainRect.size.width - (btnWidth * self.levelData.curCloNum + self.levelData.curCloNum - 1)) / 2;
    self.beginY = topLeftEmptySpace + (((mainRect.size.height - topLeftEmptySpace - GetbtmLeftEmptySpace()) - (btnWidth * self.levelData.curRowNum + self.levelData.curRowNum - 1)) / 2);
    
    GameMainView* gameView = [[GameMainView alloc] initWithLevelData:self.levelData andFrame:self.view.frame];
    [self.view addSubview: gameView];
    gameView.delegate = self;
    self.matchBtnArray = [[NSMutableArray alloc] init];
    self.matcher = [[LLKPosMatcher alloc] init];
    
    CGRect adRect = CGRectZero;
    NSString *adID = @"ca-app-pub-3929411149753833/5178502907";
    
    if (isPhone())
        adRect = CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 50);
    else
        adRect = CGRectMake(0, self.view.bounds.size.height - 90, self.view.bounds.size.width, 90);
    
    GADBannerView *tempBanner = [[GADBannerView alloc]initWithFrame:adRect];
    tempBanner.adUnitID = adID;
    tempBanner.delegate = self;
    tempBanner.rootViewController = self;
    [self.view addSubview:tempBanner];
    self.banner = tempBanner;
    
    [self.banner loadRequest:[GADRequest request]];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(20, 20, 40, 20);
    [backBtn addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitle:NSLocalizedString(@"back",nil) forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    backBtn.backgroundColor = [UIColor orangeColor];
    [self addCAEmitterLayer];
}

- (void)nextGamePassBtnClicked
{
    for (UIView* view in [self.view subviews])
        [view removeFromSuperview];
    self.level++;
    if (self.gameMode == KClassicMode)
        self.levelData = [ClassPassMaker bulitMapWithLevel:self.level];
    else
        self.levelData = [ChallengePassMaker bulitMapWithLevel:self.level];
    
    //获取开始位置
    NSUInteger btnWidth = GetBtnSizeByDevice();
    CGRect mainRect = [UIScreen mainScreen].bounds;
    self.beginX = (mainRect.size.width - (btnWidth * self.levelData.curCloNum + self.levelData.curCloNum - 1)) / 2;
    self.beginY = topLeftEmptySpace + (((mainRect.size.height - topLeftEmptySpace - GetbtmLeftEmptySpace()) - (btnWidth * self.levelData.curRowNum + self.levelData.curRowNum - 1)) / 2);

    
    GameMainView* gameView = [[GameMainView alloc] initWithLevelData:self.levelData andFrame:self.view.frame];
    [self.view addSubview: gameView];
    gameView.delegate = self;
    self.matchBtnArray = [[NSMutableArray alloc] init];
    self.matcher = [[LLKPosMatcher alloc] init];
    
    CGRect adRect = CGRectZero;
    NSString *adID = @"ca-app-pub-3929411149753833/5178502907";
    
    if (isPhone())
        adRect = CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 50);
    else
        adRect = CGRectMake(0, self.view.bounds.size.height - 90, self.view.bounds.size.width, 90);
    
    GADBannerView *tempBanner = [[GADBannerView alloc]initWithFrame:adRect];
    tempBanner.adUnitID = adID;
    tempBanner.delegate = self;
    tempBanner.rootViewController = self;
    [self.view addSubview:tempBanner];
    self.banner = tempBanner;
    
    [self.banner loadRequest:[GADRequest request]];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(20, 20, 40, 20);
    [backBtn addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitle:NSLocalizedString(@"back",nil) forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    backBtn.backgroundColor = [UIColor orangeColor];
    
}

- (void)reStartGameBtnClicked
{
    for (UIView* view in [self.view subviews])
        [view removeFromSuperview];
    
    if (self.gameMode == KClassicMode)
        self.levelData = [ClassPassMaker bulitMapWithLevel:self.level];
    else
        self.levelData = [ChallengePassMaker bulitMapWithLevel:self.level];
    
    //获取开始位置
    NSUInteger btnWidth = GetBtnSizeByDevice();
    CGRect mainRect = [UIScreen mainScreen].bounds;
    self.beginX = (mainRect.size.width - (btnWidth * self.levelData.curCloNum + self.levelData.curCloNum - 1)) / 2;
    self.beginY = topLeftEmptySpace + (((mainRect.size.height - topLeftEmptySpace - GetbtmLeftEmptySpace()) - (btnWidth * self.levelData.curRowNum + self.levelData.curRowNum - 1)) / 2);

    GameMainView* gameView = [[GameMainView alloc] initWithLevelData:self.levelData andFrame:self.view.frame];
    [self.view addSubview: gameView];
    gameView.delegate = self;
    self.matchBtnArray = [[NSMutableArray alloc] init];
    self.matcher = [[LLKPosMatcher alloc] init];
    
    CGRect adRect = CGRectZero;
    NSString *adID = @"ca-app-pub-3929411149753833/5178502907";
    
    if (isPhone())
        adRect = CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 50);
    else
        adRect = CGRectMake(0, self.view.bounds.size.height - 90, self.view.bounds.size.width, 90);
    
    GADBannerView *tempBanner = [[GADBannerView alloc]initWithFrame:adRect];
    tempBanner.adUnitID = adID;
    tempBanner.delegate = self;
    tempBanner.rootViewController = self;
    [self.view addSubview:tempBanner];
    self.banner = tempBanner;
    
    [self.banner loadRequest:[GADRequest request]];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(20, 20, 40, 20);
    [backBtn addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitle:NSLocalizedString(@"back",nil) forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    backBtn.backgroundColor = [UIColor orangeColor];
}


- (void)resetLLKMap
{
    MapMaker* maker = [[MapMaker alloc] init];
    self.levelData.gameMapArray = [maker resetLLKMap:self.levelData.gameMapArray];
    GameMainView* view = [self.view subviews][0];
    [view resetLLKMapWithLevelData:self.levelData];
}

- (BOOL)removeOnePairOfMap
{
    MapMaker* maker = [[MapMaker alloc] init];
    NSArray* removePairArr = [maker removeOnePair:self.levelData.gameMapArray];
    if (removePairArr.count > 0)
    {
        [self addMatchAnimation:removePairArr];
        GameMainView* view = [self.view subviews][0];
        [view resetLLKMapWithLevelData:self.levelData];
        return true;
    }
    return false;
}


- (BOOL)addRandomPairToMap
{
    MapMaker* maker = [[MapMaker alloc] init];
    if([maker addRandomPair:self.levelData.gameMapArray WithTypeCount:self.levelData.typeCount])
    {
        GameMainView* view = [self.view subviews][0];
        [view resetLLKMapWithLevelData:self.levelData];
        return YES;
    }
    return NO;
}

- (KGameMdoe)getGameMode
{
    return self.levelData.gameMode;
}

- (NSUInteger)getGameLevel
{
    return self.level;
}


- (id<LevelData>)getLevelData
{
    return self.levelData;
}

- (BOOL)LLKBtnMatchWithPoint: (CGPoint)firstPos and: (CGPoint)sceondPos
{
    return YES;
}

- (void)errorMatch
{
    NSLog(@"匹配失败。。。。这都能错，罚你时间");
}


- (NSUInteger)GetBtnSizeByDevice
{
    if ([[UIDevice currentDevice].model isEqualToString:@"iPad"])
    {
        return 66; //iPad  就先用iPhone的1.5倍看看效果  如果不够好来这里改 其他的计算不用管。
    }
    else
    {
        return 55; //目前这个44使用iPhone6 的真机测试出来比较合适的值
    }
}




- (BOOL)LLKBtnClick:(ClickButton*)clickBtn
{
    //当个数为2的时候就进行一次匹配 不然就将btn加入到数组中来。
    BOOL isMatched = NO;
    self.matcher.LLKMapArray = self.levelData.gameMapArray;
    if (self.matchBtnArray.count == 1)
    {
        clickBtn.backgroundColor = [UIColor greenColor];
        ClickButton* firstBtn = self.matchBtnArray[0];
        if (firstBtn.index == clickBtn.index)
        {
            NSArray* resultPoints = [self.matcher LLKBtnMatchWithPoint:firstBtn.position and:clickBtn.position];
            if(resultPoints.count > 0)
            {
                self.levelData.gameMapArray[(int)clickBtn.position.y][(int)clickBtn.position.x] = [NSNumber numberWithInt:0];
                self.levelData.gameMapArray[(int)firstBtn.position.y][(int)firstBtn.position.x] = [NSNumber numberWithInt:0];
                [firstBtn removeFromSuperview];
                firstBtn = nil;
                [clickBtn removeFromSuperview];
                clickBtn = nil;
                [self addMatchAnimation: resultPoints];
                isMatched = YES;
            }
            else
            {
                clickBtn.backgroundColor = [UIColor redColor];
                firstBtn.backgroundColor = [UIColor redColor];
                [self errorMatch];
            }
        }
        else
        {
            firstBtn.backgroundColor = [UIColor redColor];
            clickBtn.backgroundColor = [UIColor redColor];
            [self errorMatch];
        }
        if (isMatched)
        {
            GameMainView* view = [self.view subviews][0];
            view.timesProgressView.progress = 1.0;
        }
        [self.matchBtnArray removeAllObjects];
    }
    else
    {
        [clickBtn setSelected:YES];
        [self.matchBtnArray addObject:clickBtn];
        clickBtn.backgroundColor = [UIColor greenColor];
    }
    return isMatched;
}

//根据坐标计算坐标 然后加动画。
- (void)addMatchAnimation: (NSArray*)resultPoints
{
    if (resultPoints.count == 0)
        return;
    NSUInteger btnWidth = GetBtnSizeByDevice();
    CGMutablePathRef path = CGPathCreateMutable();
    do
    {
        CGPoint btnPoint = [resultPoints[0] CGPointValue];
        CGPoint btnPosition = CGPointMake(self.beginX + (btnWidth + 1) * (btnPoint.x - 1) + btnWidth / 2,
                                          self.beginY + (btnWidth + 1) * (btnPoint.y - 1) + btnWidth / 2);
        
        CGPathMoveToPoint(path, NULL, btnPosition.x, btnPosition.y);
        for (int i = 1; i < resultPoints.count; ++i)
        {
            btnPoint = [resultPoints[i] CGPointValue];
            btnPosition = CGPointMake(self.beginX + (btnWidth + 1) * (btnPoint.x - 1) + btnWidth / 2,
                                      self.beginY + (btnWidth + 1) * (btnPoint.y - 1) + btnWidth / 2);
            CGPathAddLineToPoint(path, NULL, btnPosition.x, btnPosition.y);
        }
        [self addAnimationEmitter:path];

    } while (0);
    
    CFRelease(path);
}

- (void)addAnimationEmitter: (CGPathRef)path
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"emitterPosition"];
    animation.path = path;
    animation.duration = 0.5;
    animation.repeatCount = 1;
    animation.delegate = self;
    
    
    // 雪花粒子
    CAEmitterCell *cell2 = [self productEmitterCellWithContents:(id)[[UIImage imageNamed:@"flake.png"] CGImage]];
    cell2.scale = 0.1;
    cell2.scaleRange = 0.1;
    
    // 星星粒子
    CAEmitterCell *cell1 = [self productEmitterCellWithContents:(id)[[UIImage imageNamed:@"star1.png"] CGImage]];
    cell1.scale = 0.3;
    cell1.scaleRange = 0.1;
    

    
    self.emitterLayer.emitterCells = @[cell1, cell2];
    [self.emitterLayer addAnimation:animation forKey:nil];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    [self.emitterLayer removeAllAnimations];
    [self.emitterLayer setEmitterCells:nil];
}

- (void)addCAEmitterLayer
{
    CAEmitterLayer *emitterLayer = [[CAEmitterLayer alloc] init];
    
    emitterLayer.emitterPosition = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);    // 坐标
    emitterLayer.emitterSize = self.view.bounds.size;            // 粒子大小
    emitterLayer.renderMode = kCAEmitterLayerBackToFront;      // 递增渲染模式
    emitterLayer.emitterMode = kCAEmitterLayerPoints;       // 粒子发射模式（面发射）
    emitterLayer.emitterShape = kCAEmitterLayerSphere;      // 粒子形状（球状）
    
    self.emitterLayer = emitterLayer;
    [self.view.layer addSublayer:self.emitterLayer];
}


- (CAEmitterCell *)productEmitterCellWithContents:(id)contents
{
    CAEmitterCell *cell = [CAEmitterCell emitterCell];
    cell.birthRate = 50;       // 每秒产生粒子数
    cell.lifetime = 0.2;          // 每个粒子的生命周期
    cell.lifetimeRange = 0.2;
    cell.contents = contents;   // cell内容，一般是一个CGImage
    cell.color = [[UIColor colorWithRed:0xcd green:0 blue:0xcd alpha:0.8] CGColor];
    cell.velocity = 50;         // 粒子的发射方向
    cell.emissionLongitude = M_PI*2;
    cell.emissionRange = M_PI*2;
    cell.velocityRange = 10;
    cell.spin = 10;
    cell.alphaRange = 0.1;
    
    return cell;
}

- (void)adViewDidReceiveAd:(GADBannerView *)view
{
    NSLog(@"...adViewDidReceiveAd...");
}

- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error
{
    NSLog(@"...didFailToReceiveAdWithError...%@...",error);
}



- (void)goToBack
{
    GameMainView* view = [self.view subviews][0];
    [view.totalTimer invalidate];
    view.totalTimer = nil;
    [view.timerTimer invalidate];
    view.timerTimer = nil;
    [view.resetMapTimer invalidate];
    view.resetMapTimer = nil;
    [view.addRandomPairTimer invalidate];
    view.addRandomPairTimer = nil;
    
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)resetAllSubViewFrame
{
    //调整广告条的位置
    
    CGRect adRect = CGRectZero;
    if (isPhone())
    {
        adRect = CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 50);
    }
    else
    {
        adRect = CGRectMake(0, self.view.bounds.size.height - 90, self.view.bounds.size.width, 90);
    }
    
    self.banner.frame = adRect;
}

@end
